package com.copera.cn.kaka;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.copera.cn.kaka.adapter.ShopFootImageAdapter;
import com.copera.cn.kaka.picpopupwindow.SelectPicPopupWindow;
import com.copera.cn.kaka.util.ActionUrls;
import com.copera.cn.kaka.util.HttpUtils;
import com.copera.cn.kaka.util.JsonUtil;
import com.copera.cn.kaka.util.UploadUtil;
import com.copera.cn.kaka.util.Utility;
import com.copera.cn.kaka.vo.ExchangeRuleVo;
import com.copera.cn.kaka.vo.ImageVO;
import com.copera.cn.kaka.vo.ShopVo;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ShopActivity extends BaseActivity{
	private RelativeLayout rl;//兑换礼品
	private RelativeLayout trackRL;//足迹
	private RelativeLayout photoRL;//拍照
	private TextView ms_text1,ms_text2,ms_tv7,ms_tv10,ms_tv13,ms_tv16,img_01;
	public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
	private ApplicationCustomer appc;
	private Button ms_btset;
	private String shopId;
	private int num = 0;
	private ListView listView;
	private View footview;
	private ShopFootImageAdapter shopImageAdapter;
	private List<ImageVO> vos = new ArrayList<ImageVO>();
	List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>();
	// 自定义的弹出框类
    private SelectPicPopupWindow menuWindow;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_myshop);
		appc = (ApplicationCustomer) getApplication();
		initViews();
		initEvent();
		initSet();
		listView.addFooterView(footview);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int displayWidth = dm.widthPixels;
		shopImageAdapter = new ShopFootImageAdapter(vos, this, getAppCustomer(),
				handler,displayWidth);
		listView.setAdapter(shopImageAdapter);
		//强制为竖屏 
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
	private void initViews(){
		rl = (RelativeLayout)findViewById(R.id.ms_rl27);
		footview= getLayoutInflater().inflate(R.layout.shop_foot, null);
	    trackRL = (RelativeLayout)findViewById(R.id.ms_rl26);
	    photoRL = (RelativeLayout)findViewById(R.id.ms_rl2);
	    ms_btset = (Button)findViewById(R.id.ms_btset);
	    ms_text1 = (TextView)findViewById(R.id.ms_text1);
	    ms_text2 = (TextView)findViewById(R.id.ms_text2);
	    ms_tv7 = (TextView)findViewById(R.id.ms_tv7);
	    ms_tv10 = (TextView)findViewById(R.id.ms_tv10);
	    ms_tv13 = (TextView)findViewById(R.id.ms_tv13);
	    ms_tv16 = (TextView)findViewById(R.id.ms_tv16);
	    img_01 = (TextView)findViewById(R.id.img_01);
	    listView = (ListView)findViewById(R.id.listView);
	}
	//兑换规则
	private void initSet(){
		ShopVo shop = appc.getShop();
		List<ExchangeRuleVo> list = shop.getRuleList();
		Map<String,Object> listItem;
		for (ExchangeRuleVo er : list) {
			listItem = new HashMap<String,Object>();
			listItem.put("content", er.getPointCount()+"卡点兑换"+er.getExchangeContent());
		    listItems.add(listItem);
		}
		SimpleAdapter simpleAdapter = new SimpleAdapter(this
                , listItems
                , R.layout.shop_rule_list
                , new String[]{"content"}
                , new int[]{R.id.ms_tv3});
        ListView listView = (ListView)findViewById(R.id.rule_list);
		listView.setAdapter(simpleAdapter);
		setListViewHeightBasedOnChildren(listView);
	}
	private void initValues(){
		ShopVo shop = appc.getShop();
		ms_text1.setText(shop.getShopName());
		ms_text2.setText(shop.getAddress());
		ms_tv7.setText(shop.getTrackToday());
		ms_tv10.setText(shop.getExchangeToday());
		ms_tv13.setText(shop.getPraiseCount());
		ms_tv16.setText(shop.getShareCount());
		shopId = shop.getId();
		
		
	}
	private void initEvent(){
		rl.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(ShopActivity.this,MyShopTableHostActivity.class);
			    startActivity(intent);
			}
		});
        trackRL.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(ShopActivity.this,MyShopTrackTableHostActivity.class);
			    startActivity(intent);
			}
		});
        ms_btset.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(ShopActivity.this,ShopSetHomeActivity.class);
			    startActivity(intent);
			}
		});
        photoRL.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 实例化SelectPicPopupWindow
				menuWindow = new SelectPicPopupWindow(ShopActivity.this,itemsOnClick);
				// 显示窗口
				menuWindow.showAtLocation(
						findViewById(R.id.main),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置 

			}
		});
	}

	
	private Uri photoUri;
	private String picPath;
	private void doPhoto(int requestCode, Intent data) {

		if (requestCode == SELECT_PIC_BY_PICK_PHOTO) // 从相册取图片，有些手机有异常情况，请注意
		{
			if (data == null) {
				Toast.makeText(ShopActivity.this, "选择图片文件出错", Toast.LENGTH_LONG).show();
				return;
			}
			photoUri = data.getData();
			if (photoUri == null) {
				Toast.makeText(ShopActivity.this, "选择图片文件出错", Toast.LENGTH_LONG).show();
				return;
			}
		}
		String[] pojo = { MediaStore.Images.Media.DATA };

		//Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
		ContentResolver cr = getContentResolver();
		Cursor cursor=cr.query(photoUri, pojo, null, null, null);
		if (cursor != null) {
			int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
			cursor.moveToFirst();
			picPath = cursor.getString(columnIndex);
			cursor.close();
		}

		if (picPath != null
				&& (picPath.endsWith(".png") || picPath.endsWith(".PNG")
						|| picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {
			String[] paths = null;
		
			Bitmap bp = Utility.getimage(picPath);
			File file = null;
			try {
				 file = UploadUtil
						.saveMyBitmap(bp);
				 bp = Utility.getimage(file.getAbsolutePath());
				 BitmapDrawable bd = new BitmapDrawable(Utility.small(bp));
				 photoRL.setBackgroundDrawable(bd);
				 upload(picPath);
				
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			

		} else {
			Toast.makeText(ShopActivity.this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
		}
	}
    
	@Override
	protected void onResume() {
		loadLogomage();
		loadSetData();
		initValues();
		initLoadImage();
		super.onResume();
	}
	@SuppressWarnings("deprecation")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		 if (resultCode == 10) { 
			 
				BitmapDrawable bd = new BitmapDrawable(Utility.small(appc.getBmImage()));
			 photoRL.setBackgroundDrawable(bd);
			 upload(appc.getBmystp());
		 }else if (resultCode == Activity.RESULT_OK) {
				doPhoto(requestCode, data);
				
			}
		super.onActivityResult(requestCode, resultCode, data);
		
		
		
		
	}
    public void upload(String picturePath){
    	BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(picturePath, opts);
		             
		opts.inSampleSize = Utility.computeSampleSize(opts, -1, 128*128);       
		opts.inJustDecodeBounds = false;

		UploadUtil uploadUtil = UploadUtil.getInstance();
		File file= null;
		
		try {
			file = UploadUtil.saveMyBitmap(BitmapFactory.decodeFile(picturePath, opts));
		} catch (IOException e) {
		
			e.printStackTrace();
		}

		Map<String, String> params = new HashMap<String, String>();
		params.put("shopId", shopId);
		params.put("type","");
		params.put("flag","shop_img");
		uploadUtil.uploadFile(file.getAbsolutePath(), "pic",ActionUrls.URL_UPLOAD, params);
		try {
			Thread.sleep(600);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
		loadImage();
    }
	

	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	// 为弹出窗口实现监听类
	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			menuWindow.dismiss();
			Intent intent = null;
			int id = v.getId();
			if (id == R.id.btn_take_photo) {
				
				intent = new Intent(ShopActivity.this,PhotoActivity.class);
				startActivityForResult(intent, 100);
				overridePendingTransition(R.layout.push_left_in, R.layout.push_left_out);
			} else if (id == R.id.btn_pick_photo) {
				intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
				appc.setSelectType("zm");
			} else {
				//finish();
			}

		}
	};	
    public void setListViewHeightBasedOnChildren(ListView listView) {   
    	
    	// 获取ListView对应的Adapter   
        ListAdapter listAdapter = listView.getAdapter();   
        if (listAdapter == null) {   
            return;   
        }   
    	   
    	int totalHeight = 0;   
    	for (int i = 0, len = listAdapter.getCount(); i < len; i++) {   
    		// listAdapter.getCount()返回数据项的数目   
	        View listItem = listAdapter.getView(i, null, listView);   
	        // 计算子项View 的宽高   
	        listItem.measure(0, 0);    
	        // 统计所有子项的总高度   
	        totalHeight += listItem.getMeasuredHeight();    
	    }          
       
        ViewGroup.LayoutParams params = listView.getLayoutParams();   
    	    params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));   
    	    // listView.getDividerHeight()获取子项间分隔符占用的高度   
    	    // params.height最后得到整个ListView完整显示需要的高度   
    	    listView.setLayoutParams(params);   
    } 
  //加载图片
  	private void loadImage() {
  		new AsyncTask<String, Integer, BitmapDrawable>() {
  			@Override
  			protected  BitmapDrawable doInBackground(String... params) {
  				BitmapDrawable bd;
  				try {
  					String url = ActionUrls.URL_SHOP_IMG + "?shopId="+shopId;
  					String json = HttpUtils.get(url, getAppCustomer().getHttpClient());
  					JSONObject jo = new JSONObject(json);
  					JSONObject jsonObject = jo.getJSONObject("shopImage");
  					bd = new BitmapDrawable(Utility.small(getPic(ActionUrls.HOST_IMG+jsonObject.getString("fileName"))));
  					return bd;
  				} catch (Exception e) {
  					e.printStackTrace();
  					return null;
  				}
  			}
  			@SuppressWarnings("deprecation")
			protected void onPostExecute(BitmapDrawable bd) {
  				num = 1;
  				if (bd != null) {
  					photoRL.setBackgroundDrawable(bd);
				}	
			}
  		}.execute("");
  	}
  	//加载页面时，读取图片
  	private void initLoadImage() {
  		new AsyncTask<String, Integer, BitmapDrawable>() {
  			@Override
  			protected  BitmapDrawable doInBackground(String... params) {
  				BitmapDrawable bd;
  				try {
  					String url = ActionUrls.URL_SHOP_IMG + "?shopId="+shopId;
  					String json = HttpUtils.get(url, getAppCustomer().getHttpClient());
  					JSONObject jo = new JSONObject(json);
  					JSONObject jsonObject = jo.getJSONObject("shopImage");
  					bd = new BitmapDrawable(Utility.small(getPic(ActionUrls.HOST_IMG+jsonObject.getString("fileName"))));
  					return bd;
  				} catch (Exception e) {
  					e.printStackTrace();
  					return null;
  				}
  			}
  			@SuppressWarnings("deprecation")
			protected void onPostExecute(BitmapDrawable bd) {
  				if(num == 0){
  					if (bd != null) {
  	  					photoRL.setBackgroundDrawable(bd);
  					}
  					bd = null;
  				}
			}
  		}.execute("");
  	}
  //加载图片
  	private void loadSetData() {
  		shopImageAdapter.clear();
  		new AsyncTask<String, Integer, List<ImageVO>>() {

  			@Override
  			protected  List<ImageVO> doInBackground(String... params) {
  			
  				try {
  					List<ImageVO> images = loadSetImage();
  					return images;
  				} catch (Exception e) {
  					e.printStackTrace();
  				}
  				return null;
  			}

  			@Override
  			protected void onPostExecute( List<ImageVO> images) {

  				if (images != null&&images.size()>0) {
  					try {
  						vos.addAll(images);
  					} catch (Exception e) {
  						e.printStackTrace();
  						if (e.getMessage() != null) {

  						}
  					}
  				}
  				shopImageAdapter.notifyDataSetChanged();
  				setListViewHeightBasedOnChildren(listView);
  			}

  		}.execute("" );
  	}
    	private  List<ImageVO> loadSetImage()
  			throws ClientProtocolException, IOException, JSONException {
  		String url = ActionUrls.URL_SHOP_SETIMG + "?shopId="+ getAppCustomer().getShop().getId();
  		String json = HttpUtils.get(url, getAppCustomer().getHttpClient());
  		JSONObject jo = new JSONObject(json);
  		JSONArray ts = jo.getJSONArray("list");
  		List<ImageVO> list = JsonUtil.toShopImageVo(ts);
  		
  		return list;
  	}
    //加载logo图片
  	private void loadLogomage() {
  		new AsyncTask<String, Integer, BitmapDrawable>() {
  			@SuppressWarnings("deprecation")
			@Override
  			protected  BitmapDrawable doInBackground(String... params) {
  				BitmapDrawable bd;
  				try {
  					bd=new BitmapDrawable(Utility.small(getPic(ActionUrls.HOST_IMG+appc.getShop().getHeadImage()))); 
  					return bd;
  				} catch (Exception e) {
  					e.printStackTrace();
  				}
  				return null;
  			}
  			protected void onPostExecute(BitmapDrawable bd) {
  				if (bd != null) {
  					img_01.setBackgroundDrawable(bd);
				}
			}

  		}.execute("");
  	}
	public Bitmap getPic(String uriPic) {
	    URL imageUrl = null;
	    Bitmap bitmap = null;
	    try {
	        imageUrl = new URL(uriPic);
	    } catch (MalformedURLException e) {
	        e.printStackTrace();
	    }
	    try {
	        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
	        conn.connect();
	        int nRC = conn.getResponseCode();//得到连接状态
	        if(nRC == HttpURLConnection.HTTP_OK){
	        	InputStream is = conn.getInputStream();
		        bitmap = BitmapFactory.decodeStream(is);
		 
		        is.close();
	        }
	 
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return bitmap;
	}

}
